const {createCanvas,loadImage} = require('canvas')
const ratio =0.1
function watermark(pic,wm) {
    loadImage(pic).then((myimg)=>{
        loadImage(wm).then(wmimg=>{
            const canvas = createCanvas(myimg.width,myimg.height)
            const ctx = canvas.getContext('2d')
            ctx.drawImage(myimg,0,0)

            const long = Math.sqrt(wmimg.width*wmimg.width +wmimg.height*wmimg.height)
            const halflong = long/2
            //背景图的最长边
            const bglong = Math.max(myimg.width,myimg.height)
            //贴图的缩放比
            const signscale = bglong / long * ratio
            //贴图画布边长按比例缩放
            const vmlong = long * signscale
            //创建贴图的画布
            const canvas1 = createCanvas(vmlong,vmlong)
            //获取贴图的绘图区
            const ctx1 = canvas1.getContext('2d')
            //贴图的绘图区缩放
            ctx1.scale(signscale,signscale)
            //贴图的绘图区移到中心点
            ctx1.translate(halflong,halflong)
            //贴图围绕中心点旋转
            ctx1.rotate((Math.random() -0.5) * Math.PI/2)
            //贴图的绘图区返回原点
            ctx1.translate(-halflong,-halflong)
            //在贴图的绘图区中心点绘制贴图
            ctx1.drawImage(wmimg,(long-wmimg.width)/2,(long-wmimg.height)/2)
            //随机生成贴图绘制在底图上的位置
            const posx = (myimg.width-vmlong)*Math.random()
            const posy = (myimg.height-vmlong)*Math.random()
            ctx.drawImage(canvas1,posx,posy)
            const fs =require('fs')
            const out = fs.createWriteStream(__dirname+'/'+pic)
            const stream = canvas.createPNGStream()
            stream.pipe(out)
            out.on('finish',()=>console.log("the png file is created."))
        })
    })
}

module.exports = watermark
